package com.ftg.learn.chapter09.base01;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 类工厂
 * 容器类 : 类的实例化，好处：不用每一次都实例化了，所有人都容器拿到全是唯一个实例
 * IOC : 控制反转
 * 把类的实例放到容器 里， 从容器里面拿出来
 * 池化 ：
 *
 * @author 布衣
 */
public class BeanFactory {

    //容器 Map
    private static Map<Object, Object> container = new ConcurrentHashMap<>();

    /**
     * 注册类
     *
     * @param beans 参数
     */
    public static void registerClass(Class... beans) throws InstantiationException, IllegalAccessException {
        //beans循环  实例
        for (int i = 0; i < beans.length; i++) {
            Object instance = beans[i].newInstance();
            //存储beans beans.put()
            container.put(beans[i], instance);
        }
    }


    public static void registerClass(String path) {

    }

    public static Object getBeans(Class key) {
        return container.get(key);
    }

    public static void main(String[] args) {
        try {
            BeanFactory.registerClass(Bear.class, Flies.class, Bird.class);

            Bear bear = (Bear) BeanFactory.getBeans(Bear.class);

            //单例模式 ：
            Flies flies = (Flies) BeanFactory.getBeans(Flies.class);
            Flies flies1 = (Flies) BeanFactory.getBeans(Flies.class);
            Flies flies2 = (Flies) BeanFactory.getBeans(Flies.class);
            flies.age = 34;

            System.out.println(flies1.age);

            System.out.println(flies == flies1);

        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
